package org.jmc.refmanager.web.wicket.page.panel;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.jmc.refmanager.util.Util;

/**
 */
public class ChangePanel extends Panel {
	private static final long serialVersionUID = 1L;

	public ChangePanel(String id, IModel<?> model, Object oldValue) {
		super(id, model);
		
		String beforeValue = getStringValue(oldValue);
		String afterValue = getStringValue(getDefaultModelObject());
		
		boolean hasChanged = !Util.equals(beforeValue, afterValue);;
		
		Image imgChange = new Image("beforeValue");
		imgChange.setVisibilityAllowed(hasChanged);
		
		if (hasChanged) {
			imgChange.add(new AttributeModifier("src", true, 
					new Model<String>("styles/warning.gif" )));

			imgChange.add(new SimpleAttributeModifier("title", beforeValue));
		}
		add(imgChange);
		add(new Label("value", model));
	}

	/**
	 * @param beforeValue
	 * @return
	 */
	private String getStringValue(Object value) {
		String stringValue = null;
		
		if (value instanceof Date) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			stringValue = dateFormat.format(value);
		} else {
			stringValue = Util.ifNullOrEmpty(value, "n/a");
		}
		
		return stringValue;
	}

}

